<template>
	<div class="wrapper">
		<div class="title">基本信息</div>
		<div class="info">
			<van-cell-group inset>
				<van-field :readonly="route.query.phoneNo && route.query.phoneNo !== 'undefined'" required
					v-model="phoneNo" label="手机号" placeholder="请输入手机号" />
				<!-- <van-field required v-model="address" label="所属地区" placeholder="省/市/区" /> -->
			</van-cell-group>
		</div>
		<div class="title">认证信息</div>
		<div class="info">
			<van-cell-group inset>
				<div class="form">
					<div class="upload">
						<div class="left" @click="info">
							<van-uploader :before-read="file => afterReadUploadImg(file, 'idCardFrontBase64')">
								<img class="uploadImg"
									:src="form.idCardFrontBase64 ? form.idCardFrontBase64 : idCardFront" alt="" />
							</van-uploader>
							<div class="uploader_title">身份证人像照</div>
						</div>
						<div class="right">
							<van-uploader :before-read="file => afterReadUploadImg(file, 'idCardBackBase64')">
								<img class="uploadImg" :src="form.idCardBackBase64 ? form.idCardBackBase64 : idCardBack"
									alt="" />
							</van-uploader>
							<div class="uploader_title">身份证国徽照</div>
						</div>
					</div>
				</div>
				<van-field required v-model="legalPerson" label="姓名" placeholder="请输入姓名" />
				<van-field required v-model="identityNo" label="身份证号" placeholder="请输入身份证号" />
			</van-cell-group>
		</div>
		<div class="title">结算信息</div>
		<div class="info">
			<van-cell-group inset>
				<div class="form">
					<div class="upload">
						<div class="left">
							<van-uploader :before-read="file => afterReadUploadImg(file, 'bankCardFrontBase64')">
								<img class="uploadImg"
									:src="form.bankCardFrontBase64 ? form.bankCardFrontBase64 : bankCardFront" alt="" />
							</van-uploader>
							<div class="uploader_title">银行卡正面照</div>
						</div>
					</div>
				</div>
				<van-field required v-model="bankAccountNo" label="卡号" placeholder="请输入结算卡号" />
				<van-field @click="goBank" required v-model="bankNameZh.HEAD_BANK_NAME" readonly clickable
					:is-link="true" label="开户总行" placeholder="开户总行选择" />
				<!-- <van-field
                    @click="goBank"
                    required
                    v-model="bankNameZh.HEAD_BANK_NAME"
                    readonly
                    clickable
                    :is-link="true"
                    label="开户支行"
                    placeholder="开户支行选择"
                /> -->
				<van-field required v-model="phone" label="手机号" placeholder="银行预留手机号" />
			</van-cell-group>
		</div>
		<div class="btn" @click="subMitService">确 定</div>
		<transition name="van-slide-down">
			<div class="pouple" v-if="visible">
				<div class="pouple_box">
					<div class="specification">
						相册权限说明
					</div>
					<div class="pouple_font">
						便于您使用该功能上传您的照片/图片及用于新增服务商场景中读取和写入相册和文件内容
					</div>
				</div>
			</div>
		</transition>

	</div>
</template>
<script>
	export default {
		name: 'addService' //命名组件
	}
</script>
<script setup name="addService">
	import idCardFront from '@/assets/auth/cardface.png'
	import idCardBack from '@/assets/auth/card.png'
	import bankCardFront from '@/assets/auth/bank.png'
	import store from '@/store'
	import {
		showToast,
		showDialog
	} from 'vant'
	import {
		addAgentExpand,
		checkImage,
		optimizeAgentExpand,
		uploadMerchantPic
	} from '@/api/service'
	import {
		convertImg
	} from '../../utils/compressor.js'
	// import { premissionCheck } from '../../utils/permission.js'
	const router = useRouter()
	const route = useRoute()
	const form = ref({})
	const phoneNo = ref('')
	const filePaths = ref({
		localIdCardFrontPath: '', // 身份证人像面(本地)
		channelIdCardFrontPath: '', // 身份证人像面(渠道)
		localIdCardBackPath: '', // 身份证国徽面(本地)
		channelIdCardBackPath: '', // 身份证国徽面(渠道)
		localBankCardFrontPath: '', // 银行卡卡号面(本地)
		channelBankCardFrontPath: ''
	})
	const legalPerson = ref('')
	const bankAccountNo = ref('')
	const readonly = ref(false)

	const profitSettleType = ref('')
	const phone = ref('')
	// const address = ref("")
	const bankNameZh = ref({}) // 总行
	const bankName = ref({}) // 支行
	const addressObj = ref({}) // 归属地
	const identityNo = ref('')
	const visible = ref(false)

	if (route.query.agentNo) {
		document.title = '认证合伙人'
	}
	// url地址会默认转换为字符串的undefined
	if (route.query.identityNo && route.query.identityNo !== 'undefined') {
		readonly.value = true
		identityNo.value = route.query.identityNo
	}
	if (route.query.phoneNo && route.query.phoneNo !== 'undefined') {
		phoneNo.value = route.query.phoneNo
	}
	onActivated(() => {
		bankNameZh.value = store.state.data.BANK
	})
	const goBank = () => {
		router.push({
			path: '/bankList'
		})
	}
	const checkPermission = () => {
		const permission = 'android.permission.READ_EXTERNAL_STORAGE' // 要检查的权限
		plus.android.checkPermission(
			permission,
			granted => {
				// 0(已获取权限) -1未获取权限
				if (granted.checkResult == -1) {
					console.log(JSON.stringify(granted), 'Permission granted')
					showToast('上传图片,需要同意并开启存储权限')
				} else if (granted.checkResult == 0) {
					console.log(granted, 'Permission none')
				}
			},
			error => {
				console.error('Error checking permission:', error.message)
			}
		)
	}
	const info = () => {
		const permission = 'android.permission.READ_EXTERNAL_STORAGE' // 要检查的权限
		plus.android.checkPermission(
			permission,
			granted => {
				// 0(已获取权限) -1未获取权限
				if (granted.checkResult == -1) {
					visible.value = true
				} else if (granted.checkResult == 0) {
					
				}
				
			},
			error => {
				console.error('Error checking permission:', error.message)
			}
		)
		const permissionCAMERA = 'android.permission.CAMERA' // 要检查的权限
		plus.android.checkPermission(
			permissionCAMERA,
			granted => {
				// 0(已获取权限) -1未获取权限
				if (granted.checkResult == -1) {
					visible.value = true
				} else if (granted.checkResult == 0) {
					visible.value = false
				}
				
			},
			error => {
				console.error('Error checking permission:', error.message)
			}
		)
		plus.android.requestPermissions(['android.permission.READ_EXTERNAL_STORAGE','android.permission.CAMERA'],
			(e) => {	
				//关闭
				visible.value = false
				if (e.granted.length > 0) {
					//执行你有权限后的方法
				}
			})
	}
	const afterReadUploadImg = (file, key) => {
		convertImg(file).then(res => {
			form.value[key] = res
			showToast('上传图片,需要同意并开启存储权限')
			if (key === 'idCardFrontBase64' || key === 'bankCardFrontBase64') {
				checkImage({
					content: res,
					imageType: key === 'idCardFrontBase64' ? 'idcard' : 'bankCard'
				}).then(result => {
					let cardInfo = JSON.parse(result.object).result
					if (key === 'idCardFrontBase64') {
						let cardInfo = JSON.parse(result.object).words_result
						console.log(readonly.value, 'eadonly.value')
						// var result = premissionCheck("EXTERNAL_STORAGE")

						if (!readonly.value) {
							identityNo.value = cardInfo['公民身份号码'].words
						}
						console.log(cardInfo, 'cardInfo')
						legalPerson.value = cardInfo['姓名'].words
					}
					if (key === 'bankCardFrontBase64') {
						bankAccountNo.value = cardInfo.bank_card_number.replace(/\s/g, '')
					}
				})
			}
		})
	}
	const subMitService = () => {
		console.log(phoneNo, 'phoneNo.value')
		if (phoneNo.value == '' && !phoneNo.value.length) {
			showToast('请输入手机号')
			return
		}
		// if (address.value == "" || !address.value.length) {
		//     showToast("请输入所属地区")
		//     return
		// }
		if (legalPerson.value == '' || !legalPerson.value.length) {
			showToast('请输入姓名')
			return
		}
		if (identityNo.value == '' || !identityNo.value.length) {
			showToast('请输入身份证号')
			return
		}
		if (bankAccountNo.value == '' || !bankAccountNo.value.length) {
			showToast('请输入卡号')
			return
		}
		if (!bankNameZh.value.HEAD_BANK_NAME) {
			showToast('请选择开户总行')
			return
		}
		if (phone.value == '' || !phone.value.length) {
			showToast('请输入银行预留手机号')
			return
		}
		let data = {
			agentBean: {
				phoneNo: phoneNo.value,
				legalPerson: legalPerson.value,
				identityNo: identityNo.value,
				profitSettleType: store.state.user.userInfo.agentBean.profitSettleType,
				organCode: addressObj.value.organCode,
				agentNo: route.query.agentNo
			},
			settleInfoBean: {
				bankAccountNo: bankAccountNo.value,
				bankCode: bankNameZh.value.HEAD_BANK_CODE,
				alliedBankCode: bankName.value.BANK_CODE,
				prePhone: phone.value
			}
		}
		data.idCardFrontBase64 = form.value.idCardFrontBase64
		data.idCardBackBase64 = form.value.idCardBackBase64
		data.bankCardFrontBase64 = form.value.bankCardFrontBase64
		if (route.query.agentNo && route.query.agentNo != 'undefined') {
			optimizeAgentExpand(data).then(res => {
				const {
					code,
					object
				} = res
				if (code === 200) {
					showDialog({
						title: '标题',
						message: '认证成功，请重新登录'
					}).then(() => {
						uni.reLaunch({
							url: '/pages/login'
						})
					})
				}
			})
		} else {
			data.agentBean.agentNo = undefined
			addAgentExpand(data).then(res => {
				showDialog({
					message: '提交成功',
					confirmButtonColor: '#66d6ff'
				}).then(() => {
					router.go(-1)
				})
			})
		}
	}
</script>

<style scoped lang="scss">
	.wrapper {
		.title {
			text-align: center;
			font-size: 16px;
			font-weight: 400;
			color: #000000;
			padding: 10px;
		}

		.btn {
			width: 160px;
			height: 40px;
			background: #66d6ff;
			border-radius: 6px;
			font-size: 14px;
			font-weight: 400;
			color: #ffffff;
			display: flex;
			margin: 24px auto;
			align-items: center;
			justify-content: center;
		}
	}

	.form {
		background: #fffffe;

		.uploader_title {
			text-align: center;
			padding: 10px;
		}

		.upload {
			padding: 10px;
			display: flex;
			justify-content: space-between;

			.uploadImg {
				border-radius: 10px;
				width: 150px;
				height: 90px;
			}
		}

		.infoMax {
			padding: 0px 20px 10px 20px;
		}

		.info {
			background: #ffffff;
			box-shadow: 0px 0px 10px #ececec;
			opacity: 1;
			border-radius: 20px;
			padding: 10px;
			display: flex;
			align-items: center;
			font-size: 12px;
			font-family: 'Avenir', Helvetica, Arial, sans-serif;

			span {
				margin-left: 5px;
			}

			font-weight: 400;
			color: #717882;
			opacity: 1;
		}
	}

	.pouple {
		display: flex;
		position: absolute;
		top: 4px;
		align-items: center;
		justify-content: center;

		.pouple_box {
			width: 92%;
			background-color: #fff;
			padding: 8px 12px 12px 12px;
			border-radius: 4px;
			line-height: 18px;
		}

		.pouple_font {
			margin-top: 6px;
			font-size: 14px;
		}

		.specification {
			font-size: 16px;
			font-weight: bold;
		}
	}
</style>